package com.efuture.servlet.cookie;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @description: Cookie案例
 * 需求：
 * 	1. 访问一个Servlet，如果是第一次访问，则提示：您好，欢迎您首次访问。
 * 	2. 如果不是第一次访问，则提示：欢迎回来，您上次访问时间为:显示时间字符串
 * @author zhaoshanshan
 * @date 2021/10/3 6:24 下午
 * @version 1.0
 */

@WebServlet("/ApplyCookie")
public class ApplyCookie extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        //获取cookie
        Cookie[] cookies = request.getCookies();
        boolean flag = false;//标记是否有latsTime这个cookie
        if(null!=cookies&&cookies.length>0){//有cookie数据
            //遍历cookie
            for (Cookie cookie :cookies) {
                String name = cookie.getName();
                if(null!=name&&name.equals("lastTime")){
                    flag = true;
                    //不是第一次访问
                    //获取上次的访问时间
                    String value = cookie.getValue();
                    value = URLDecoder.decode(value,"utf-8");
                    // 修改cookie lasttime时间
                    //获取当前系统时间
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("YYYY-mm-dd HH:mm:ss");
                    String currentDate = sdf.format(date);
                    //时间有空格 需要编码
                    currentDate = URLEncoder.encode(currentDate,"utf-8");
                    //将当前系统时间更新cookie
                    cookie.setValue(currentDate);
                    cookie.setMaxAge(60*60*24*30);//一个月存储
                    //添加到response里
                    response.addCookie(cookie);
                    //输出到浏览器
                    response.getWriter().write("<h1>欢迎回来,上次访问时间为:"+value+"</h1>");
                    break;
                }

            }

        }

        if(null==cookies||cookies.length==0||!flag){

            //第一次访问
            //获取当前系统时间
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("YYYY-mm-dd HH:mm:ss");
            String currentDate = sdf.format(date);
            currentDate = URLEncoder.encode(currentDate,"utf-8");
            Cookie cookie = new Cookie("lastTime",currentDate);
            cookie.setMaxAge(60*60*24*30);//一个月存储
            response.addCookie(cookie);
            response.getWriter().write("<h1>您好，欢迎您首次访问</h1>");
        }

    }
}
